package br.com.windroid.conceitows;

import java.util.List;

import org.apache.http.conn.HttpHostConnectException;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import br.com.windroid.conceitows.ws.UsuarioResource;
import br.com.windroid.sigtap.seguranca.entity.Usuario;

public class UsuarioListActivity extends ListActivity {

	public static final String USUARIO_ID = "br.com.windroid.conceitows.USUARIO_ID";

	private UsuarioResource usuarioResource;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		try {
			usuarioResource = new UsuarioResource();
			initList();
		} catch (Exception e) {
			Toast.makeText(UsuarioListActivity.this, "Não foi conectou ao servidor", Toast.LENGTH_LONG).show();
			
		}
	}

	public void initList() {
		
			try {
				List<Usuario> listaUsuarios = usuarioResource.buscarUsuarios();

				setListAdapter(new ArrayAdapter<Usuario>(this, R.layout.row,listaUsuarios) {
					@Override
					public View getView(int position, View convertView, ViewGroup parent) {
						LayoutInflater inflater = getLayoutInflater();
						View row = inflater.inflate(R.layout.row, parent, false);
						
						TextView textViewNome = (TextView) row
								.findViewById(R.id.textViewNome);
						textViewNome.setText(getItem(position).getNome());
						
						TextView textViewEmail = (TextView) row
								.findViewById(R.id.textViewEmail);
						textViewEmail.setText(getItem(position).getEmail());
						
						return row;
					}
				});		
			} catch (Exception e) {
				Toast.makeText(UsuarioListActivity.this, "Não foi conectou ao servidor", Toast.LENGTH_LONG).show();
				
			}
			
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// redirecionando controle para UsuarioFormActivity
		Intent intent = new Intent(UsuarioListActivity.this,
				UsuarioFormActivity.class);
		intent.putExtra(USUARIO_ID,
				((Usuario) getListAdapter().getItem(position)).getId());
		// Torna UsuarioFormActivity ativo
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.option, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * Evento disparado ao selecionar item do menu
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.add) {
			startActivity(new Intent(UsuarioListActivity.this,
					UsuarioFormActivity.class));
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		initList();
		super.onResume();
	}

}
